package sunwul.mall.auth.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import sunwul.mall.auth.domain.LoginSysUser;
import sunwul.mall.auth.mapper.LoginSysUserMapper;
import sunwul.mall.commoncore.model.SecurityUser;
import sunwul.mall.auth.strategy.LoginStrategy;
import sunwul.mall.commonbase.constant.AuthConstants;

import java.util.Set;

/**
 * @author sunwul
 * @date 2024/12/26 14:51
 * @description 商城后台管理系统登录策略的具体实现
 */
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {

    @Autowired
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        // 根据用户名称获取用户对象
        LoginSysUser loginSysUser =
//        loginSysUserMapper.selectOne(new QueryWrapper<LoginSysUser>().eq("username", username));
                loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>()
                        .eq(LoginSysUser::getUsername, username)); // 使用方法引用获取字段的名称,避免硬编码

        if (ObjectUtil.isNull(loginSysUser)) {
            throw new UsernameNotFoundException("未获取到对应用户信息!");
        }

        // 根据用户标识查询用户的权限集合
        Set<String> perms = loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());
        // 创建安全用户对象SecurityUser
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUserId(loginSysUser.getUserId());
        securityUser.setPassword(loginSysUser.getPassword());
        securityUser.setShopId(loginSysUser.getShopId());
        securityUser.setStatus(loginSysUser.getStatus());
        securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
        // 判断用户权限
        if (CollectionUtil.isNotEmpty(perms) && perms.size() > 0) {
            securityUser.setPerms(perms);
        }

        return securityUser;
    }
}
